package cn.tinlan.shopcoin.app.koi;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.CallClazzProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.subsciber.BaseSubscriber;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.tinlan.shopcoin.R;
import cn.tinlan.shopcoin.Utils.SPUtils;
import cn.tinlan.shopcoin.Utils.ToastUtils;
import cn.tinlan.shopcoin.app.koi.adapter.KoiListAdapter;

import cn.tinlan.shopcoin.app.koi.model.KoiListItemModel;
import cn.tinlan.shopcoin.app.koi.model.KoiSeekModel;
import cn.tinlan.shopcoin.app.login.UserModel;
import cn.tinlan.shopcoin.app.mine.adress.model.AddressItemModel;
import cn.tinlan.shopcoin.base.BaseFragment;
import cn.tinlan.shopcoin.base.CustomApiResult;
import cn.tinlan.shopcoin.widget.category.Constants;
import io.reactivex.Observable;

/**
 * Created by Mortimer on 2018/12/24. 09:39
 * 佛祖🙏，永无bug。
 */
public class KoiFragment extends BaseFragment implements View.OnClickListener{

//    @BindView(R.id.dcc_notice)
//    View dccNotice;
//    @BindView(R.id.dcc_seek)
//    View dccSeek;
//    @BindView(R.id.dcc_send)
//    View dccSend;
//    @BindView(R.id.dcc_get)
//    View dccGet;
    @BindView(R.id.dcc_title)
    TitleBar titleBar;
    @BindView(R.id.dcc_refresh)
    SmartRefreshLayout sRefresh;
    @BindView(R.id.dcc_rv)
    RecyclerView mRV;


    View headView ;
    private KoiListAdapter listAdapter;

    private boolean isSend = false;
    private String tempMobile = "";
    private int page = 1;
    private List<KoiListItemModel> koiListItemModels;
    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_dcc;
    }


    @Override
    public void initView(View rootView) {
        super.initView(rootView);

//        dccNotice.setOnClickListener(this);
//        dccSeek.setOnClickListener(this);
//        dccSend.setOnClickListener(this);
//        dccGet.setOnClickListener(this);
        initTitleView();
        initRefresh();
        initRV();

    }

    private void initRV() {
        if (listAdapter == null) {
            LinearLayoutManager llm = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
            mRV.setLayoutManager(llm);
            koiListItemModels = new ArrayList<>();
//            koiListItemModels.add(new KoiListItemModel());
            listAdapter = new KoiListAdapter(R.layout.view_koi_listitem,R.layout.view_dcc_head,koiListItemModels);
            mRV.setAdapter(listAdapter);
            headView = getLayoutInflater().inflate(R.layout.view_dcc_head,(ViewGroup) mRV.getParent(), false);


            View head = headView.findViewById(R.id.dcc_head_refresh);
            TextView mobile = headView.findViewById(R.id.dcc_head_mobile);
            UserModel userModel =  SPUtils.getUserBean(mActivity);
            tempMobile = userModel.getMobile();
            mobile.setText(tempMobile);
            TextView fans = headView.findViewById(R.id.dcc_head_fans);
            fans.setText(userModel.getR_code());

            head.setOnClickListener(this);

            listAdapter.addHeaderView(headView);

        }else {
            listAdapter.notifyDataSetChanged();
        }
        listAdapter.setOnItemSubViewClickListener(new KoiListAdapter.OnItemSubViewClickListener() {
            @Override
            public void onItemStatusClick(String id) {
                if (!isSend) {
                    isSend = true;
                    KoiOK(id);
                }

            }
        });
    }


    private void initRefresh() {
        sRefresh.setRefreshHeader(new ClassicsHeader(mActivity));
        sRefresh.setRefreshFooter(new ClassicsFooter(mActivity));
        sRefresh.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        sRefresh.setEnableFooterFollowWhenLoadFinished(true);
        sRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                page++;
                loadListData(page,false);;

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

//                Log.d("test->>>","刷新完成");
                //请求数据
//                refreshLayout.finishRefresh();  //刷新完成
                page = 1;
                loadUserData();
                loadListData(page,false);

            }
        });
    }


    @Override
    protected void loadData() {


    }
    private void initTitleView() {


        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {

            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {
//                Log.d("1111","11111");
                toUserJoin();
            }
        });
    }

    @Override
    public void initData() {
        super.initData();

        page = 1;
        loadUserData();
        loadListData(page,false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.dcc_head_refresh:
                toDCCRfresh();
                break;

        }
    }

    private void loadListData(final int page1,final boolean refresh) {
//        String url = "";
//        if (listStatus == 1) {
//            url = Constants.KoiSupportPayment;
//        }else {
//            url = Constants.KoiSupportIncome;
//        }



        Observable<List<KoiListItemModel>> observable = EasyHttp.get(Constants.KoiSupportPayment)
                .params("user_id", SPUtils.getUserID(mActivity))//
                .params("page",page1+"")
                .execute(new CallClazzProxy<CustomApiResult<List<KoiListItemModel>>, List<KoiListItemModel>>(new TypeToken<List<KoiListItemModel>>() {}.getType()) {
                });

        observable.subscribe(new BaseSubscriber<List<KoiListItemModel>>() {
            @Override
            public void onError(ApiException e) {

                    sRefresh.finishRefresh();
                    sRefresh.finishLoadMore();      //加载完成

                if (page > 1){
                    page--;
                }else {
                    page = 1;
                }

//                ToastUtils.show("数据请求失败");

            }

            @Override
            public void onNext(List<KoiListItemModel> KoiListItemModels) {
                super.onNext(KoiListItemModels);
                sRefresh.finishRefresh();
                sRefresh.finishLoadMore();
//                if (KoiListItemModels.size() < 1){
//                    if (refresh){
//                        listAdapter.setNewData(KoiListItemModels);
//                    }
////                    ToastUtils.show("数据暂无");
//
//                    return;
//                }

                if (page1 == 1){
                    koiListItemModels = KoiListItemModels;
                    listAdapter.setNewData(KoiListItemModels);

//                    mShopListAdapter.notifyDataSetChanged();
                }else {

                    listAdapter.addData(KoiListItemModels);
                    if (KoiListItemModels.size() < 16) {
                        sRefresh.finishLoadMoreWithNoMoreData();  //全部加载完成,没有数据了调用此方法
                    }

//
                }

            }
        });
    }

    private void KoiOK(String id) {
//        String url = "";
//        if (listStatus == 1) {
//            url = Constants.KoiSupportPaymentOK;
//        }else {
//            url = Constants.KoiSupportIncomeOK;
//        }

        EasyHttp.post(Constants.KoiSupportPaymentOK)
                .params("id", id)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
//                        ToastUtils.show("添加失败");
                        isSend = false;
                    }

                    @Override
                    public void onSuccess(String s) {
                        isSend = false;
                        try {
                            JSONObject data = new JSONObject(s);
                            String num = data.getString("data");
                            ToastUtils.show(num);
//                            seekDCC.setText(num);
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                        page = 1;
                        listAdapter.cancelAllTimers();
                        loadListData(page,true);
                    }
                }) {
                });
    }


    private void loadUserData() {

        EasyHttp.get(Constants.KoiUserInfo)
                .params("id", SPUtils.getUserID(mActivity))//
                .execute(new CallBackProxy<CustomApiResult<KoiSeekModel>, KoiSeekModel>(new SimpleCallBack<KoiSeekModel>() {
                    @Override
                    public void onError(ApiException e) {
//                        ToastUtils.show("添加失败");

                    }

                    @Override
                    public void onSuccess(KoiSeekModel koiSeekModel) {


                        TextView mobile = headView.findViewById(R.id.dcc_head_mobile);
                        mobile.setText(koiSeekModel.getMobile());
                        TextView level = headView.findViewById(R.id.dcc_head_level);
                        level.setText(koiSeekModel.getQualification());//资格数
                        TextView fans = headView.findViewById(R.id.dcc_head_fans);
                        fans.setText(koiSeekModel.getR_code());

                        TextView paypoint = headView.findViewById(R.id.dcc_head_paypoint);
                        paypoint.setText(koiSeekModel.getShop_amount());

                        TextView head_money = headView.findViewById(R.id.dcc_head_money);
                        head_money.setText(koiSeekModel.getMoney());

                        TextView dcc = headView.findViewById(R.id.dcc_head_dccnum);
                        if (koiSeekModel.getDcc() == null || koiSeekModel.getDcc().equals("") || koiSeekModel.getDcc().equals("null")) {
                            dcc.setText("0");
                        }else {
                            dcc.setText(koiSeekModel.getDcc());
                        }


                        TextView kzpoint = headView.findViewById(R.id.dcc_head_kzpoint);
                        kzpoint.setText(koiSeekModel.getSend_amount());
                        TextView kypoint = headView.findViewById(R.id.dcc_head_kypoint);
                        kypoint.setText(koiSeekModel.getUsable_amount());


//                        ToastUtils.show("添加成功");

                    }
                }) {
                });
    }

    private void toDCCRfresh() {
        if (tempMobile.isEmpty()) return;
        EasyHttp.get(Constants.KoiRefreshDCC)
                .params("mobile", tempMobile)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.show("同步失败");

                    }

                    @Override
                    public void onSuccess(String s) {
//                        JsonObject object = new JsonObject();

                        try {
                            JSONObject data = new JSONObject(s);
                            String num = data.getString("data");
                            Log.d("refresh",num);
                            TextView dcc = headView.findViewById(R.id.dcc_head_dccnum);
                            dcc.setText(num);
                            ToastUtils.show("更新成功");
//                            seekDCC.setText(num);
                        }catch (Exception e){
                            e.printStackTrace();
                        }



//                        ToastUtils.show("添加成功");
                    }
                }) {
                });
    }


    private void toUserJoin() {
//        Log.d("11111","22222");
        EasyHttp.post(Constants.KoiNewPersonJ)
                .params("user_id", SPUtils.getUserID(mActivity))//
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        Log.d("join","shibai");
                        ToastUtils.show("加入失败");
                    }

                    @Override
                    public void onSuccess(String s) {
//                        JsonObject object = new JsonObject();

                        try {
                            JSONObject data = new JSONObject(s);
                            String code = data.getString("code");
                            if (code.equals("1")){
                                ToastUtils.show("加入成功");
                            }else {
                                String content = data.getString("data");
                                ToastUtils.show(content);
                            }

//                            Log.d("refresh",num);
//                            TextView dcc = headView.findViewById(R.id.dcc_head_dccnum);
//                            dcc.setText(num);
//                            seekDCC.setText(num);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
//                        ToastUtils.show("加入成功");
                        Log.d("join","加入成功");
                    }
                }) {
                });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden){
//            Log.d("onhidden","hidden");
            page = 1;
            loadUserData();
            loadListData(page,false);

        }
    }
}
